#C:\Clients\prague\CCH PACK>column-reorder.py D01E.csv 3,7;4,6;7,5;9,4;14,1;18,11;19,13;21,12;29,14;37,8;40,9;49,0;50,1;51,16;52,17;53,3;54,2 testing.csv

import pepe.txt.bigtxt as bt
import sys
import os
import re
import string

def args_to_dict (csv_s):
    """
    splits supplied args to list
    """
    cord = {}
    order_l = string.split(csv_s,';')
    for aim in order_l:
        cordin = string.split(aim,',')
        cord[int(cordin[0])] = int(cordin[1])
    return cord

def order_col(src_string, wantedorder, delimiter_in, delimiter_out):
    """
    reorders columns in line to desired order with chosen delimiter
    """
    src_string = re.sub("^|$","|",src_string)
    cols = string.split(src_string,delimiter_in)
    outp = ""
    for i in range(57):
        if wantedorder.has_key(i):
            outp += cols[wantedorder[i]+1] + delimiter_out
        else:
            outp += delimiter_out
    return outp[:-1] + "\n"


def main():
    if len(sys.argv) == 4:
        starter(sys.argv[1], sys.argv[2], sys.argv[3])
    else:
        print starter.__doc__; os.system('pause')

    
def starter(infile,order,outfile):
    """
    Purpose:    reorders columns in line to desired order with chosen delimiter
    Syntax:     ---.py inputfile.csv scheme outputfile.csv
    Example:    C:\Clients\prague\CCH PACK>column-reorder.py D01E.csv 3,7;4,6;7,5;9,4;14,1;18,11;19,13;21,12;29,14;37,8;40,9;49,0;50,1;51,16;52,17;53,3;54,2 testing.csv

    """
    output_s=''
    for lin in bt.lines(infile):
        output_s += order_col(lin, args_to_dict(order), '|', '|')
    output = open(outfile,'w')
    output.write (output_s)
#    print "column-reorder completed to " + outfile + "." 

if __name__ == "__main__":
    main()
